package com.csii.activiti.server.core.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.csii.activiti.server.core.constant.ActDefaultColumnConstant;
import com.csii.activiti.server.core.utils.DataSourceUtils;
import com.csii.activiti.server.core.utils.FormJsonProcessUtils;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.Properties;

@MapperScan("com.csii.**.mapper")
@EnableTransactionManagement
@Configuration
public class ActivitiMybatisPlusConfig {

    /**
     * 分页插件
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 别名
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public DatabaseIdProvider databaseIdProvider(@Value("${activity.oracle.typeName:SQL_TEXT_LIST}") String typeName){
        VendorDatabaseIdProvider vendorDatabaseIdProvider = new VendorDatabaseIdProvider(){
            @Override
            public String getDatabaseId(DataSource dataSource) {
                String databaseId = super.getDatabaseId(dataSource);
                DataSourceUtils.setCurrentDatasourceName(databaseId);
                if (DataSourceUtils.isOracle()){
                    ActDefaultColumnConstant.capitalize();
                }
                DataSourceUtils.setOracleType(typeName);
                FormJsonProcessUtils.initDBTypes();
                return databaseId;
            }
        };
        Properties properties =new Properties();
        properties.setProperty("MySQL","mysql");
        properties.setProperty("Oracle","oracle");
        vendorDatabaseIdProvider.setProperties(properties);
        return vendorDatabaseIdProvider;
    }

}
